package com.tpsix.service.impl;

import com.tpsix.util.TreeBuilder;
import org.springframework.stereotype.Service;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tpsix.mapper.SysMenuMapper;
import com.tpsix.domain.SysMenu;
import com.tpsix.service.SysMenuService;
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Override
    public List<SysMenu> menuTree(int userId) {
        List<SysMenu> sysMenus = new ArrayList<>();
        List<SysMenu> menus;
        if (userId == 0) {
            menus = this.list();
        } else {
            menus = baseMapper.findByUserId(userId);
        }

        menus.forEach(menu -> {
            if (menu.getParentId() == null || menu.getParentId() == 0) {
                menu.setLevel(0);
                if (TreeBuilder.exists(sysMenus, menu)) {
                    sysMenus.add(menu);
                }
            }
        });
        sysMenus.sort(Comparator.comparing(SysMenu::getSort));
        TreeBuilder.menuTreeBuild(sysMenus, menus, 0);
        return sysMenus;
    }

}
